package com.yang.flower.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.flower.common.Result;
import com.yang.flower.entity.*;
import com.yang.flower.mapper.OrdersMapper;
import com.yang.flower.service.*;
import com.yang.flower.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: OrdersController
 * @Author: Yang
 * @DateTime: 2022/12/7 9:52
 **/
@RestController
@CrossOrigin
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrdersFlowersService ordersFlowersService;

    @Resource
    private OrdersMapper ordersMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private FlowerService flowerService;

    @Autowired
    private UserService userService;

    //分页查询订单
    @GetMapping("/page")
    public Page<Orders> page(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam String number,
                             @RequestParam String user){
        Page<Orders> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        String userId = "";

        if (user != ""){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUsername,user);
            userId = String.valueOf(userService.getOne(userLambdaQueryWrapper).getId());
        }

        queryWrapper.like(Orders::getOrderCode,number).like(Orders::getUserId,userId);
        queryWrapper.orderByDesc(Orders::getOrderTime);

//        Page<Orders> pageInfo = ordersService.page(page, queryWrapper);
        User currentUser = TokenUtils.getCurrentUser();
        Page<Orders> pageInfo = ordersMapper.page(page,user,currentUser.getRole(),currentUser.getId(),number);

        return pageInfo;
    }

    //添加订单
    @PostMapping("/save")
    public Result save(@RequestBody Orders orders){
        if(orders.getId() == null){
            Date date = new Date();
            orders.setOrderTime(DateUtil.now());
            orders.setUserId(TokenUtils.getCurrentUser().getId());
            orders.setOrderCode(DateUtil.format(date,"yyyyMMdd") + System.currentTimeMillis());
            orders.setAddress("");
            ordersService.save(orders);
            List<Cart> carts = orders.getCarts();
            for (Cart cart : carts) {
                OrdersFlowers ordersFlowers = new OrdersFlowers();
                ordersFlowers.setFlowerId(cart.getFlowerId());
                ordersFlowers.setNum(cart.getNum());
                ordersFlowers.setOrderId(orders.getId());
                ordersFlowersService.save(ordersFlowers);
                cartService.removeById(cart.getId());
            }
        }else{
            ordersService.updateById(orders);
        }
        return Result.success();
    }

    @GetMapping("/getFlowersById/{id}")
    public Result getFlowersById(@PathVariable Integer id){
        LambdaQueryWrapper<OrdersFlowers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrdersFlowers::getOrderId,id);
        List<OrdersFlowers> ordersFlowers = ordersFlowersService.list(queryWrapper);
        List<Flower> flowerList = new ArrayList<>();
        for (OrdersFlowers ordersFlower : ordersFlowers) {
            Integer flowerId = ordersFlower.getFlowerId();
            Flower flower = flowerService.getById(flowerId);
            flower.setNum(ordersFlower.getNum());
            flowerList.add(flower);
        }
        return Result.success(flowerList);
    }

    //修改订单
    @PutMapping("/edit")
    public Result edit(@RequestBody Orders orders){
        return Result.success(ordersService.saveOrUpdate(orders));
    }

    //删除订单
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id){
        return Result.success(ordersService.removeById(id));
    }

    //批量删除订单
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<String> ids){
        return Result.success(ordersService.removeByIds(ids));
    }

    //导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Orders> list = ordersService.list();
        // 通过工具类创建writer 写出到磁盘路径
        // ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("number", "订单号");
        writer.addHeaderAlias("status", "订单状态");
        writer.addHeaderAlias("user", "下单用户");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("orderTime", "下单时间");
        writer.addHeaderAlias("checkoutTime", "结账时间");
        writer.addHeaderAlias("amount", "实收金额");
        writer.addHeaderAlias("remark", "备注");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

}
